<template>
    <div class="login-container">
        <img class="back" mode="fill" :src="coverImage('https://yun-question.oss-cn-beijing.aliyuncs.com/static/admin-bg.jpg')"/>
        <div class="form-container yx-center">
            <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form yx-str"
                autocomplete="off"
                label-position="left"
            >
                <h2 class="index-title">题库管理后台</h2>
                <el-form-item prop="username">
                    <span class="svg-container">
                        <svg-icon icon-class="user"/>
                    </span>
                    <el-input
                        v-model="loginForm.username"
                        placeholder="账号/手机号"
                        name="username"
                        type="text"
                        tabindex="1"
                        autocomplete="off"
                    />
                </el-form-item>

                <el-form-item prop="password">
                    <span class="svg-container">
                        <svg-icon icon-class="password"/>
                    </span>
                    <el-input
                        :key="passwordType"
                        ref="password"
                        v-model="loginForm.password"
                        :type="passwordType"
                        placeholder="密码"
                        name="password"
                        tabindex="2"
                        autocomplete="new-password"
                        @keyup.native="checkCapslock"
                        @blur="capsTooltip = false"
                        @keyup.enter.native="handleLogin"
                    />
                    <span class="show-pwd" @click="showPwd">
                        <svg-icon
                            :icon-class="
                                passwordType === 'password' ? 'eye' : 'eye-open'
                            "
                        />
                    </span>
                </el-form-item>

                <el-form-item :key="codeImageKey">
                    <div>
                        <el-input
                            v-model="loginForm.code"
                            placeholder="验证码"
                            class="code-input"
                            @keyup.native="checkCapslock"
                            @blur="capsTooltip = false"
                            @keyup.enter.native="handleLogin"
                        />
                        <img
                            class="code-image pointer"
                            :src="codeImg"
                            @click="codeImageKey++"
                        />

                    </div>
                    <div class="info">
                        <el-checkbox v-model="remember" class="checkBox">记住我</el-checkbox>
                        <span @click="codeImageKey++" class="code">看不清,重新获取</span>
                    </div>
                </el-form-item>
                <el-button
                    :loading="loading"
                    type="primary"
                    style="width:100%;height:50px;margin-top: 40px; font-size: 20px;"
                    size="default"
                    @click.native.prevent="handleLogin"
                >登  录
                </el-button
                >
            </el-form>
        </div>
    </div>
</template>

<script>
import {validUsername} from "@/utils/validate";
import {VuePage} from "@/layout/mixin/iVue";
import store from "@/store";

export default {
    name: "Login",
    mixins: [VuePage],
    data() {
        const validateUsername = (rule, value, callback) => {
            if (!validUsername(value)) {
                callback(new Error("请输入用户名"));
            } else {
                callback();
            }
        };
        const validatePassword = (rule, value, callback) => {
            if (value.length < 6) {
                callback(new Error("密码必须大于6位"));
            } else {
                callback();
            }
        };
        let codeImageKey = new Date().getTime();
        return {
            loginForm: {
                username: "",
                password: "",
                code: ""
            },
            remember: false,
            loginRules: {
                username: [
                    {
                        required: true,
                        trigger: "blur",
                        validator: validateUsername
                    }
                ],
                password: [
                    {
                        required: true,
                        trigger: "blur",
                        validator: validatePassword
                    }
                ]
            },
            passwordType: "password",
            capsTooltip: false,
            loading: false,
            showDialog: false,
            redirect: undefined,
            otherQuery: {},
            codeImageKey
        };
    },
    computed: {
        codeImg() {
            return `/api/yuntk/user/cu/sys/base/valid-image?red=249&green=252&blue=255&time=${this.codeImageKey}`;
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                const query = route.query;
                if (query) {
                    this.redirect = query.redirect;
                    this.otherQuery = this.getOtherQuery(query);
                }
            },
            immediate: true
        }
    },
    created() {
        // window.addEventListener('storage', this.afterQRScan)
        this.state.user.routes = [];
        this.state.user.roles = null;

    },
    mounted() {
        if (this.loginForm.username === "") {
            this.$refs.username.focus();
        } else if (this.loginForm.password === "") {
            this.$refs.password.focus();
        }
        let username = localStorage.getItem("username")
        let password = localStorage.getItem("password")
        if (username && password) {
            this.loginForm.username = username;
            this.loginForm.password = password;
            this.remember=true;
        }
    },
    destroyed() {
        // window.removeEventListener('storage', this.afterQRScan)
    },
    methods: {
        checkCapslock(e) {
            const {key} = e;
            this.capsTooltip =
                key && key.length === 1 && key >= "A" && key <= "Z";
        },
        showPwd() {
            if (this.passwordType === "password") {
                this.passwordType = "";
            } else {
                this.passwordType = "password";
            }
            this.$nextTick(() => {
                this.$refs.password.focus();
            });
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$store
                        .dispatch("user/login", this.loginForm)
                        .then(() => {
                            if (this.redirect === "/403") {
                                this.$router.push({path: "/"});
                                return;
                            }
                            if (this.remember) {
                                localStorage.setItem("username", this.loginForm.username)
                                localStorage.setItem("password", this.loginForm.password)
                            }else{
                                localStorage.removeItem("username")
                                localStorage.removeItem("password")
                            }
                            console.log("登陆成功",this.redirect)
                            this.$router.push({
                                path: this.redirect || "/",
                                query: this.otherQuery
                            });

                            this.loading = false;
                            setTimeout(() => {
                                this.codeImageKey++;
                            }, 1000);
                        })
                        .catch(() => {
                            this.loading = false;
                            this.codeImageKey++;
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        getOtherQuery(query) {
            return Object.keys(query).reduce((acc, cur) => {
                if (cur !== "redirect") {
                    acc[cur] = query[cur];
                }
                return acc;
            }, {});
        }
    }
};
</script>

<style lang="scss" scoped>
.login-container {
    position: relative;

    .back {
        position: absolute;
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        object-fit: cover;
    }

    .form-container {
        position: absolute;
        width: 100vw;
        height: 100vh;
        padding-right: 11.5vw;
        align-items: flex-end;

        .login-form {
            box-shadow: 20px 19px 2px 0px RGBA(86, 97, 156), 40px 40px 2px 0px RGBA(86, 97, 156, .8);
            width: 389px;
            height: 557px;
            box-sizing: border-box;
            padding: 80px 40px 80px 40px;
            border-radius: 5px;
            background-color: white;

            .info {
                position: relative;

                .checkBox {
                    position: absolute;
                    left: 0;
                    color: #868EA1;
                }

                .code {
                    position: absolute;
                    right: 0;
                    user-select: none;
                    color: #868EA1;
                    cursor: pointer;
                }

            }

            .logo {
                width: 100%;
                margin-bottom: 50px;
            }
            .index-title{
                margin-bottom: 30px;
                text-align: center;
            }
            .code-input {
                width: 150px;

                ::v-deep input {
                    padding: 0 8px !important;
                }
            }

            .code-image {
                width: 118px;
                height: 48px;
                border-radius: 6px;
                position: absolute;
                right: 0;
                border: 1px #e4e7eb solid;
            }

            .el-form-item {
                height: 48px;
                position: relative;

                .svg-container {
                    position: absolute;
                    z-index: 1;
                    width: 39px;
                    height: 48px;
                    line-height: 48px;
                    text-align: center;
                    color: #c4c9d7;
                }

                .show-pwd {
                    position: absolute;
                    z-index: 1;
                    right: 0;
                    width: 39px;
                    height: 48px;
                    line-height: 48px;
                    text-align: center;
                    color: #c4c9d7;
                }

                ::v-deep .el-input {
                    display: inline-block;

                    input {
                        background: #f9fcff;
                        height: 48px;
                        border: 1px #e4e7eb solid;
                        -webkit-appearance: none;
                        border-radius: 6px;
                        padding: 0 39px;
                        color: #333;
                        caret-color: #000;
                        font-size: 16px;

                        &:-webkit-autofill {
                            box-shadow: 0 0 0px 1000px #fff inset !important;
                            -webkit-text-fill-color: #333 !important;
                        }
                    }
                }
            }
        }
    }
}
</style>
